package com.ljl.question2.tcp;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.Closeable;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * tcp连接器
 *
 * @author ljl
 */
public class TcpConnector implements Closeable {
    private final Logger logger = LogManager.getLogger(TcpConnector.class);

    private final ExecutorService executor = Executors.newSingleThreadExecutor();

    private String uuid;

    private String ip;

    private int port;

    /**
     * 已发送消息的次数
     */
    private AtomicInteger counter = new AtomicInteger(0);

    private Socket socket;

    private OutputStream outputStream;

    public String getIp() {
        return ip;
    }

    public int getPort() {
        return port;
    }

    public int getCounter() {
        return counter.get();
    }

    public String getUuid() {
        return uuid;
    }

    public void start() throws IOException {
        // 清空资源
        close();
        try {
            this.socket = new Socket();
            this.socket.connect(new InetSocketAddress(ip, port));
            this.outputStream = this.socket.getOutputStream();
            logger.info("tcp connect to {}:{} success", ip, port);
            executor.execute(() -> {
                while (true) {
                    try {
                        this.outputStream.write((System.currentTimeMillis() + "\r\n").getBytes(StandardCharsets.UTF_8));
                        this.outputStream.flush();
                        counter.addAndGet(1);
                        Thread.sleep(1000);
                    } catch (InterruptedException | IOException e) {
                        logger.error("exception:{}", e.getMessage());
                        try {
                            close();
                        } catch (IOException ex) {
                            logger.error("exception:{}", e.getMessage());
                            break;
                        }
                        break;
                    }
                }
            });
        } catch (IOException e) {
            logger.error("exception:{}", e.getMessage());
            close();
            throw new RuntimeException(e);
        }
    }

    @Override
    public void close() throws IOException {
        this.counter = new AtomicInteger(0);
        if (this.outputStream != null) {
            this.outputStream.close();
        }
        if (this.socket != null) {
            this.socket.close();
        }
    }
}
